//
//  HeartRateDetailController.swift
//  MoyoungHome
//
//  Created by 易先生 on 2022/9/20.
//

import UIKit
import MYModule
import JXSegmentedView
import RxSwift
import RxCocoa

class HeartRateDetailController: BaseViewController {
    
    var viewModel = HeartRateProvider(date: Date())

    /// 是否显示right item
    public var showRightItem: Bool = true
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavigationBar()
        
        
    }
    
    func setNavigationBar() {
        
        navigation.bar.backgroundColor = UIColor.background
        navigation.item.title = "heart_rate_title".language
        
        if showRightItem {
            navigation.item.rightBarButtonItems = [rightBarButtonItem, historyBarButtonItem]
        }
    }

    
	override func makeUI() {
		super.makeUI()

        indicator.indicatorColor = UIColor.HeartRate.theme
        indicator.layer.shadowColor = UIColor.HeartRate.theme.cgColor
		segmentDataSource.titleNormalColor = UIColor.assist_A9A9A9
        segmentedView.delegate = self

        pointView.pointColors = UIColor.HeartRate.assist_slider
        pointView.imgColor = UIColor.assist_FFFFFF
        
        
        self.zoneView.backgroundColor = UIColor.background
        self.zoneView.hourLabel.text = "--"
        self.zoneView.minuteLabel.text = "--"

        self.zoneView.descriptionView.backgroundColor = UIColor.background
        self.zoneView.descriptionView.updateData(textColor: UIColor.HeartRate.theme, title: "heart_rate_zone_description_title".language, explain: "heart_rate_zone_description_content".language,
                                                 explainTextColor: UIColor.HeartRate.theme.withAlphaComponent(0.8),
                                                 bgColor: UIColor.HeartRate.theme)
        
        segmentedView.dataSource = segmentDataSource
        segmentedView.indicators = [indicator]

        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(topLayoutGuide.snp.bottom)
            make.leading.trailing.bottom.equalToSuperview()
        }

        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.centerX.equalToSuperview()
        }

        contentView.addSubview(segmentedView)
        segmentedView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(70)
        }
        
       

        contentView.addSubview(dayBarChartView)
        dayBarChartView.snp.makeConstraints { make in
            make.top.equalTo(segmentedView.snp.bottom)
            make.leading.trailing.equalToSuperview()
        }
        
        contentView.addSubview(weekBarChartView)
        weekBarChartView.snp.makeConstraints { make in
            make.edges.equalTo(dayBarChartView)
        }
        
        contentView.addSubview(monthBarChartView)
        monthBarChartView.snp.makeConstraints { make in
            make.edges.equalTo(dayBarChartView)
        }
        
        
        contentView.addSubview(pointView)
        pointView.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.height.equalTo(180)
            make.width.equalTo(50)
            make.bottom.equalTo(dayBarChartView.snp.bottom).offset(20)
        }

    
        self.dayBarChartView.isHidden = false
        self.weekBarChartView.isHidden = true
        self.monthBarChartView.isHidden = true
        
        contentView.addSubview(self.zoneView)
        self.zoneView.snp.makeConstraints { make in
            make.top.equalTo(pointView.snp.bottom).offset(10)
			make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
		}
        

	}

	override func bindViewModel() {
		super.bindViewModel()
        
        historyBarButtonItem.rx.tap.subscribe { [weak self] _ in
            guard let self = self else { return }
            
            let vc = HistoryController()
            vc.showType = .heart
            self.navigationController?.pushViewController(vc, animated: true)
            
        }.disposed(by: rx.disposeBag)
        
		rightBarButtonItem.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }
			let vc = CalendarController()
			vc.showType = .heart24h
			vc.reloadRelay.subscribe(onNext: { date in
				self.viewModel.date = date
				self.viewModel.updateData()
			}).disposed(by: self.rx.disposeBag)
			self.navigationController?.pushViewController(vc, animated: true)
		}.disposed(by: rx.disposeBag)

		viewModel.updateData()

		viewModel.curDayChart.subscribe(onNext: { [weak self] heartRateModel in
			guard let self = self, let heartRateModel = heartRateModel else { return }

            let date = heartRateModel.date
           
            self.dayBarChartView.dateString = date.localString + " " + "unit_average".language
            self.dayBarChartView.heartAvg = heartRateModel.heartAvg

            self.dayBarChartView.barChartView.max = Double(heartRateModel.chartMaxData)
            self.dayBarChartView.barChartView.min = Double(heartRateModel.chartMinData)

            self.dayBarChartView.bind(to: .day,
                                      barDatas: heartRateModel.chartDatas,
                                      YAxisMaxValue: heartRateModel.chartMaxData,
                                      YAxisMinValue: heartRateModel.chartMinData,
                                      YAxisLineCount: heartRateModel.chartYAxisCount)


		}).disposed(by: rx.disposeBag)

        viewModel.weekChart.subscribe(onNext: {[weak self] heartRateModel in

            guard let self = self, let model = heartRateModel else { return }
            
            self.weekBarChartView.dateString = model.date.localweekRangeString + " " + "unit_average".language

            self.weekBarChartView.bind(type: .week,
                                       date: model.date,
                                       barDatas: model.chartDatas,
                                           allAvg: model.heartAvg,
                                           YAxisMaxValue: model.chartMaxData,
                                           YAxisminValue: model.chartMinData,
                                           YAxisLineCount: model.chartYAxisCount)
            
            
        }).disposed(by: rx.disposeBag)

        viewModel.monthChart.subscribe(onNext: {[weak self] heartRateModel in
            
            guard let self = self, let model = heartRateModel else { return }
            
            self.monthBarChartView.dateString = model.date.localMonthRangeString + " " + "unit_average".language
            
            self.monthBarChartView.bind(type: .month,
                                        date: model.date,
                                        barDatas: model.chartDatas,
                                        allAvg: model.heartAvg,
                                        YAxisMaxValue: model.chartMaxData,
                                        YAxisminValue: model.chartMinData,
                                        YAxisLineCount: model.chartYAxisCount)
            
            
        }).disposed(by: rx.disposeBag)
        

		viewModel.heartRateZoneRelay.subscribe(onNext: { [weak self] dataModel in
			guard let self = self else { return }
            self.zoneView.bind(to: dataModel)
		}).disposed(by: rx.disposeBag)
        
        pointView.rx.panGesture().when(.changed).subscribe(onNext: { [weak self] gesture in
            guard let `self` = self else { return }
            
            let point = gesture.location(in: self.view)
            
            let w = self.pointView.width / 2 - 2
            if point.x < w || point.x > kScreenWidth - w  {
                return
            }
            self.pointView.centerX = point.x
            
            let centenrPoint = CGPoint(x: point.x + self.pointView.width/2.0, y: point.y)
            let dayChartPoint = self.view.convert(centenrPoint, to: self.dayBarChartView)
            
            self.dayBarChartView.slider(dayChartPoint)
            self.weekBarChartView.slider(point)
            self.monthBarChartView.slider(point)
            
        }).disposed(by: rx.disposeBag)
        
        let panGesture = pointView.rx.panGesture().when(.ended).mapToVoid().asDriverOnErrorJustComplete()
        panGesture.delay(RxTimeInterval.seconds(3)).drive(onNext: {[weak self] _ in
            
            guard let self = self else { return }
            
            let chartPoint = CGPoint.zero
            self.dayBarChartView.slider(chartPoint)
            
            self.weekBarChartView.clearHighlight()
            self.monthBarChartView.clearHighlight()
            
            self.pointView.left = 0
            
        }).disposed(by: rx.disposeBag)
        
        

	}
    
    public lazy var historyBarButtonItem: UIBarButtonItem = {
        let historyBarButtonItem = UIBarButtonItem()
        historyBarButtonItem.image = UIImage(named: "ic_data")
        return historyBarButtonItem
    }()

    public lazy var rightBarButtonItem: UIBarButtonItem = {
        let rightBarButtonItem = UIBarButtonItem()
        rightBarButtonItem.image = UIImage(named: "ic_date")
        return rightBarButtonItem
    }()

    public lazy var scrollView: ScrollView = {
        let view = ScrollView()
        view.showsVerticalScrollIndicator = false
        view.backgroundColor =  UIColor.darkBackground
        view.bounces = false
        return view
    }()

    public lazy var contentView: View = {
        let view = View()
        view.backgroundColor =  UIColor.darkBackground
        return view
    }()

    public lazy var segmentedView: JXSegmentedView = {
        let segmentedView = JXSegmentedView()
        segmentedView.commonConfig(backgroundColor: UIColor.background)
        return segmentedView
    }()
    
    
    lazy var indicator: JXSegmentedIndicatorBackgroundView = {
        let indicator = JXSegmentedIndicatorBackgroundView()
        
        indicator.commonConfig(shadowColor: UIColor.Step.theme)
        
        return indicator
    }()

    lazy var segmentDataSource: JXSegmentedTitleDataSource = {
        let datasource = JXSegmentedTitleDataSource()
        
        datasource.commonConfig(titles: [
            "heart_rate_day_title".language,
            "heart_rate_week_title".language,
            "heart_rate_month_title".language])
        
        
        return datasource
    }()


    public lazy var dayBarChartView: HeartRateBarChartView = {
        let barChartView = HeartRateBarChartView()
        barChartView.backgroundColor = UIColor.background
        barChartView.setRoundedCorners(.bottom, radius: 18)
        return barChartView
    }()
    public lazy var weekBarChartView: HeartRateWeekMonthChartView = {
        let barChartView = HeartRateWeekMonthChartView()
      
        barChartView.backgroundColor = UIColor.background
        barChartView.setRoundedCorners(.bottom, radius: 18)
        return barChartView
    }()
    public lazy var monthBarChartView: HeartRateWeekMonthChartView = {
        let barChartView = HeartRateWeekMonthChartView()
        barChartView.backgroundColor = UIColor.background
        barChartView.setRoundedCorners(.bottom, radius: 18)
        return barChartView
    }()

    public lazy var pointView: DataPointView = {
        let pointView = DataPointView()
        return pointView
    }()

	

    private lazy var zoneView: HeartRateZoneView = {
        let view = HeartRateZoneView()
        view.setRoundedCorners(.all, radius: 18)
        return view
    }()
    

}

extension HeartRateDetailController: JXSegmentedViewDelegate {

	func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        
        
        self.dayBarChartView.isHidden = index != 0
        self.weekBarChartView.isHidden = index != 1
        self.monthBarChartView.isHidden = index != 2
        
	}
}
